package com.youan.pangu.core.mvc.handler;

import com.youan.pangu.base.bean.result.AbsResponseBean;
import com.youan.pangu.base.bean.result.ErrorResponse;
import com.youan.pangu.base.bean.result.ErrorType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 辛晟昊
 * @time: 2020/3/4 15:46
 */
@ControllerAdvice
public class GlobalErrorHandler {
    private Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

    @ExceptionHandler(BindException.class)
    public AbsResponseBean bindExceptionHandler(BindException e){
        logger.error(e.getMessage());
        List<String> defaultMsg = e.getBindingResult().getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.toList());
        AbsResponseBean responseBean = new ErrorResponse(defaultMsg.toString(), ErrorType.VALIDATE_ERROR);
        return responseBean;
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public AbsResponseBean validationErrorHandler(ConstraintViolationException e) {
        logger.error(e.getMessage());
        AbsResponseBean responseBean = new ErrorResponse(e.getMessage(), ErrorType.VALIDATE_ERROR);
        return responseBean;
    }

    @ExceptionHandler(Exception.class)
    public AbsResponseBean exceptionErrorHandler(Exception e){
        logger.error(e.getMessage());
        AbsResponseBean responseBean = responseBean = new ErrorResponse(e.getMessage());
        return responseBean;
    }
}
